package service;

import dao.BookingMapper;
import entity.Booking;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.session.SqlSession;
import utils.MyBatisUtil;

import java.util.ArrayList;
import java.util.List;

public class BookingService {
    /**
     * 编写查询方法，查询所有预约信息，查询结果按接种状态和预约接种日期升序排列
     * @param pageIndex
     * @param pageSize
     * @return
     */
    public List<Booking> list(@Param("pageIndex") Integer pageIndex, @Param("pageSize")Integer pageSize){
        List<Booking> list = new ArrayList<Booking>();
        SqlSession sqlSession = null;
        try{
            sqlSession = MyBatisUtil.createSqlSession();
            list = sqlSession.getMapper(BookingMapper.class).list(pageIndex, pageSize);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            MyBatisUtil.closeSqlSession(sqlSession);
        }
        return list;

    }

    /**
     * 将新的预约信息保存到数据库
     * @param booking
     * @return
     */
    public int add(Booking booking){
        int count =0;
        SqlSession sqlSession =null;
        try{
            sqlSession = MyBatisUtil.createSqlSession();
            count = sqlSession.getMapper(BookingMapper.class).add(booking);
            sqlSession.commit();
        }catch (Exception e){
            e.printStackTrace();
            sqlSession.rollback();
        }finally {
            MyBatisUtil.closeSqlSession(sqlSession);
        }

        return count;
    }

    /**
     * 编写修改方法，修改指定的预约信息，将接种状态改为“已接种”
     * @param status
     * @param id
     * @return
     */
    public int update(@Param("status")int status,@Param("id")Integer id){
        int count =0;
        SqlSession sqlSession=null;
        try {
            sqlSession=MyBatisUtil.createSqlSession();
            count=sqlSession.getMapper(BookingMapper.class).update(status, id);
            sqlSession.commit();
        }catch (Exception e){
            e.printStackTrace();
            sqlSession.rollback();
        }finally {
            MyBatisUtil.closeSqlSession(sqlSession);
        }

        return count;
    }

    /**
     * 编写修改方法，删除指定的接种信息
     * @param id
     * @return
     */
    public int del(@Param("id")Integer id){
        int count =0;
        SqlSession sqlSession =null;
        try {
            sqlSession=MyBatisUtil.createSqlSession();
            count =sqlSession.getMapper(BookingMapper.class).del(id);
            sqlSession.commit();
        }catch (Exception e){
            e.printStackTrace();
            sqlSession.rollback();
        }finally {
            MyBatisUtil.closeSqlSession(sqlSession);
        }

        return count;
    }
}
